package tests;

import jBittorrentAPI.ConnectionManager;
import jBittorrentAPI.TorrentProcessor;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class SuperPeer {	
	public static void main(String[] args) {
		/*
		 * args
		 */
		String torrentPath = null;
		String videoPath = null;
		
		String trackerAnnounceURL = null;
		String trackerUploadURL = null;
		String trackerUsername = null;
		String trackerPassword = null;
		
		int pieceLength = 0;

		String torrentCreator = null;
		String torrentComment = null;
		String torrentTrackerComment = null;
		
		int minPort = 0;
		int maxPort = 0;
		
		if(args.length < 5) {
			printError();
		} else {
			torrentPath = args[0];
			trackerAnnounceURL = args[1];
			
			try {
				pieceLength = Integer.parseInt(args[2]);
			} catch(Exception e) {
				printError();
				return;
			}
			
			videoPath = args[3];
			torrentCreator = args[4];
			torrentComment = args[5];
			
			trackerUploadURL = args[6]; 
			trackerUsername = args[7];
			trackerPassword = args[8];
			torrentTrackerComment = args[9];
			
			try {
				minPort = Integer.parseInt(args[10]);
				maxPort = Integer.parseInt(args[11]);
			} catch(Exception e) {
				printError();
				return;
			}
		}

		/*
		 * create torrent file
		 */
		if(!createTorrentFile(torrentPath, trackerAnnounceURL, pieceLength, videoPath, torrentCreator, torrentComment)) {
			printError();
			return;
		}
		
		/*
		 * publish torrent file
		 */
		if(!publishTorrent(torrentPath, trackerUploadURL, trackerUsername, trackerPassword, torrentTrackerComment)) {
			printError();
			return;
		}
		
		/*
		 * share video
		 */
		new Peer("s", torrentPath, minPort, maxPort, 0, 0); 
	}
	
	private static void printError() {
		System.out.println("Error!");
	}

	private static boolean createTorrentFile(String torrentPath, String trackerAnnounceURL, int pieceLength, String videoPath, String creator, String comment) {
		TorrentProcessor tp = new TorrentProcessor();
		tp.setAnnounceURL(trackerAnnounceURL);
		tp.setPieceLength(pieceLength);
		
		ArrayList<String> files = new ArrayList<String>();
		files.add(videoPath);
		try {
			tp.addFiles(files);
		} catch (Exception e1) {
			return false;
		}

		tp.setCreator(creator);
		
		tp.setComment(comment);

		try{
			tp.generatePieceHashes();
			FileOutputStream fos = new FileOutputStream(torrentPath);
			fos.write(tp.generateTorrent());
			return true;
		} catch(Exception e) {
			return false;
		}
	}
	
	private static boolean publishTorrent(String torrentPath, String trackerUploadURL, String trackerUsername, String trackerPassword, String torrentTrackerComment) {
        File f = new File(torrentPath);
        try{
            ConnectionManager.publish(torrentPath, trackerUploadURL, trackerUsername, trackerPassword, f.getName(), "", torrentTrackerComment, "7");
            return true;
        }catch(Exception e){
        	return false;
        }
	}
}
